package org.apereo.cas.web.controller;

import com.github.ghsea.sso.client.security.permission.RestResponse;
import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.apereo.cas.web.dto.RolesAndPermissions;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author guhai
 * @since 2021/6/14 20:53
 */
@RestController
@RequestMapping(path = "/authority")
public class PermissionController {

    private Map<String, List<String>> id2Permissions = new HashMap<>();

    private Map<String, List<String>> mail2Permissions = new HashMap<>();

    private Map<String, List<String>> id2Roles = new HashMap<>();

    private Map<String, List<String>> mail2Roles = new HashMap<>();

    @PostConstruct
    private void initMockPermissionsAndRoles() {
        id2Permissions.put("1", Arrays.asList("user:list", "user:list2"));
        mail2Permissions.put("ghsea2018@xxx.com", Arrays.asList("user:list", "user:list2"));
        id2Roles.put("1", Arrays.asList("admin", "operator"));
        mail2Roles.put("ghsea2018@xxx.com", Arrays.asList("admin", "operator"));
    }

    @RequestMapping(value = "/roleAndPermission")
    public RestResponse<RolesAndPermissions> hello(@RequestParam(name = "id", required = false) String id,
                                                   @RequestParam(name = "mail", required = false) String mail,
                                                   HttpServletRequest request) {
        Preconditions.checkArgument(StringUtils.hasText(id) || StringUtils.hasText(mail));
        if (StringUtils.hasText(id)) {
            List<String> permissions = id2Permissions.getOrDefault(id, Collections.emptyList());
            List<String> roles = id2Roles.getOrDefault(id, Collections.emptyList());
            RolesAndPermissions rolesAndPermissions = new RolesAndPermissions().setRoles(roles).setPermissions(permissions);
            return new RestResponse().setData(rolesAndPermissions);
        }

        List<String> permissions = mail2Permissions.getOrDefault(mail, Collections.emptyList());
        List<String> roles = mail2Roles.getOrDefault(mail, Collections.emptyList());
        RolesAndPermissions r = new RolesAndPermissions().setRoles(roles).setPermissions(permissions);
        return new RestResponse().setData(r);
    }

    private void validateToken(HttpServletRequest request) {
        System.out.println(request.getHeader("Keep-Alive"));
    }
}
